package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.service.WxAPIService;
import cn.com.connext.scrm.service.dto.JsonResult;
import cn.com.connext.scrm.service.mapper.ThirdPartyService;
import cn.com.connext.scrm.web.rest.errors.MyErrorCode;
import cn.com.connext.scrm.web.rest.vm.CardSignatureVM;
import com.alibaba.fastjson.JSON;
import com.connext.common.exception.ServiceException;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;

/**
 * 微信公众号三方授权
 */
@RestController
@RequestMapping("/wx/threeSide/")
public class WxThreeSideResource {
    private final Logger logger = LoggerFactory.getLogger(WxThreeSideResource.class);

    @Autowired
    private ThirdPartyService thirdPartyService;

    @Autowired
    private WxAPIService wxAPIService;

    /**
     * 获取票据
     */
    @ApiOperation(value = "接收component_verify_ticket 或 authorized事件", notes = "接收component_verify_ticket 或 authorized事件")
    @PostMapping(value = "getComponentVerifyTicket")
    public void getComponentVerifyTicket(HttpServletRequest request, @RequestBody(required = false) String postData) throws Exception {
        logger.info("接收component_verify_ticket 或 authorized事件:{}", postData);
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String msgSignature = request.getParameter("msg_signature");
        logger.info("nonce: " + nonce);
        logger.info("timestamp: " + timestamp);
        logger.info("msgSignature: " + msgSignature);
        logger.info("postData: " + postData);
        thirdPartyService.getComponentVerifyTicket(timestamp, nonce, msgSignature, postData);
//        return "success";
    }

    /**
     * 获取授权地址
     */
    @ApiOperation(value = "获取三方授权地址", notes = "获取三方授权地址")
    @PostMapping(value = "bindcomponent")
    public String bindcomponent() {
        return thirdPartyService.bindcomponent();
    }

    /**
     * 根据auth_code查询授权信息 授权回调
     *
     * @param authCode  授权成功时获得的授权码
     * @param expiresIn 存活时间
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryAuth")
    public String queryAuth(@RequestParam("auth_code") String authCode, @RequestParam("expires_in") String expiresIn) {
        logger.info("公众号授权回调auth_code={},expires_in={}", authCode, expiresIn);
        thirdPartyService.queryAuth(authCode, expiresIn);
        return "授权成功";
    }

    /**
     * 获取签名
     */
    @ResponseBody
    @RequestMapping(value = "/getCardSignature")
    public JsonResult getCardSignature(@RequestBody CardSignatureVM req) throws Exception {
        if (StringUtils.isEmpty(req.getCardId())) {
            throw new ServiceException(MyErrorCode.ERROR_INPUT);
        }
        logger.info("获取签名,cardId={}", req.getCardId());
        JsonResult jsonResult = thirdPartyService.getCardSignature(req.getCardId());
        return jsonResult;
    }

    /**
     * 第三方平台回调
     */
    @ResponseBody
    @PostMapping(value = "/callback/{appid}")
    public String callback(@PathVariable String appid, @RequestBody(required = false) String content) {
//        String param = "appid:" + appid
//            + "\nsignature:" + signature
//            + "\ntimestamp:" + timestamp
//            + "\nnonce:" + nonce
//            + "\nencrypt_type:" + encrypt_type
//            + "\nmsg_signature:" + msg_signature
//            + "\nechostr:" + echostr
//            + "\ncontent:" + content;
        logger.info("第三方回调callback：{}", appid);
        logger.info("第三方回调callback：{}", content);

        return "success";
    }
}

